<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/Store for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Estore\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Estore\Model\Storeproducts;
use Estore\Model\Storeorders;

//use Estore\Model\StoreproductsTable;
//use Estore\Model\StoreordersTable;

use Estore\Form\StoreproductsForm;

use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;

use Zend\Stdlib\DateTime;

class EstoreController extends AbstractActionController
{
    public function indexAction()
    {
    	// grab the paginator from the Store Product
    	$ProductsTable = $this->getServiceLocator()->get('ProductsTable');
    	//$paginator = $this->getAlbumTable()->fetchAll(true);
    	$paginator = $ProductsTable->fetchAll(true);
    	// set the current page to what has been passed in query string, or to 1 if none set
    	$paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
    	// set the number of items per page to 10
    	$paginator->setItemCountPerPage(8);
    	//throw new \Exception(var_dump($paginator));
    	return new ViewModel(array(	'paginator' => $paginator));
    	//return new ViewModel();
   		//return array();
    }
    
    public function productDetailAction()
    {  	
    	$request = $this->getRequest();
    	
    	if ($request->isPost()) 
    	{
    		$choose = $request->getPost('choose', 'Purchase');
    		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($del));
    		if ($choose == 'Purchase') {
    			$productId = (int) $request->getPost('id');
    			$qnt = 	(int) $request->getPost('qnt');	
    			//store data in Orders Table
    			$Storeproducts = new Storeproducts();
    			//$productId = $request->getPost('id');
    			//$productId = $this->params()->fromRoute('id');
    			//$qnt = $this->params()->fromRoute('qnt');
    			$productTable = $this->getServiceLocator()->get('ProductsTable');
    			$product = $productTable->getStoreproducts($productId);
    			/////////////////////////////////////////////////////////////
    			$userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
    			$userEmail = $this->getAuthService()->getStorage()->read();
    			$user = $userTable->getUserByEmail($userEmail);
    			////////////////////////////////////////////////////////////////
    			//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($user));
    			$date = new DateTime();
    			$exchange_data = array();
    			$exchange_data['id'] = 0;
    			$exchange_data['store_product_id'] = $product->id;
    			$exchange_data['qty'] = $qnt;
    			$exchange_data['total'] = $qnt*$product->cost;
    			$exchange_data['status'] = 'New';
    			$exchange_data['stamp'] = $date->setTimestamp(); // getTimestamp();date('Y-m-d H:i:s');
    			$exchange_data['first_name'] = $user->name;
    			$exchange_data['last_name'] = '';
    			$exchange_data['email'] = $userEmail;
    			$exchange_data['ship_to_street'] = '';
    			$exchange_data['ship_to_city'] = '';
    			$exchange_data['ship_to_state'] = '';
    			$exchange_data['ship_to_state'] = '';
    			$exchange_data['ship_to_zip'] = '';
    			//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($exchange_data));
    			////////////////////////////////////////////////////////////////
    			$order = new Storeorders();
    			$order->exchangeArray($exchange_data);
    			$ordersTable = $this->getServiceLocator()->get('OrdersTable');
    			$ordersTable->saveStoreorders($order);
    			$lastorder = $ordersTable->getlastorder();
    			// Redirect to list shoping Cart	
    			//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($lastorder));
    			return $this->redirect()->toRoute('estore',
    					array('action' => 'shoppingCart','id'=>$productId,'qnt'=>$qnt,'orderid'=>$lastorder,),
    					array('qnt'=>$qnt,)
    			);
    			//return $this->url('estore',array('action' => 'shoppingCart','id'=>$id,),array('qnt'=>$qnt));'product'=>$product,
    		}
    		// Redirect to list shoping Cart
    		return $this->redirect()->toRoute('estore',array('action' => 'index'));
    		//return $this->url('estore',array('action' => 'shoppingCart','id'=>$id,),array('qnt'=>$qnt));
    	
    	}
    	else
    	{
    		$productId = $this->params()->fromRoute('id');
    		$productTable = $this->getServiceLocator()->get('ProductsTable');
    		$product = $productTable->getStoreproducts($productId);
    		$viewModel = new ViewModel(array('product' => $product));
    	}
    	
    	//return new ViewModel();
    	return $viewModel; 
    }
    
    public function shoppingCartAction()
    {
    	$productId = $this->params()->fromRoute('id');
    	$qnt = $this->params()->fromRoute('qnt');
    	$orderid = $this->params()->fromRoute('orderid');
    	
    	$productTable = $this->getServiceLocator()->get('ProductsTable');
    	$product = $productTable->getStoreproducts($productId);
    	//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($qnt));
    	$viewModel = new ViewModel(array('product' => $product,'qnt'=>$qnt,'orderid'=>$orderid));
    	
    	return $viewModel;
    }
    
    public function paypalExpressCheckoutAction()
    {
    	$request = $this->getRequest();
    	$orderId = $this->params()->fromRoute('orderid'); //$request->getPost()->get('orderid');
    	$productId = $this->params()->fromRoute('id');
    	//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($orderId));
    	$orderTable = $this->getServiceLocator()->get('OrdersTable');
    	$order = $orderTable->getStoreorders($orderId);
    	//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($order));
    	$paypalRequest = $this->getPaypalRequest();
    	$paymentDetails = new \SpeckPaypal\Element\PaymentDetails
    	(array('amt' => $order->total
    	));
    	$express = new \SpeckPaypal\Request\SetExpressCheckout(
    			array('paymentDetails' => $paymentDetails)
    	);
    	$confirmadress = 'http://bupiotr.my.phpcloud.com/Project_01/estore/payment-confirm/'.$productId;
    	$express->setReturnUrl(
    			//'http://comm-app.local/users/store/paymentConfirm');
    	        //'http://bupiotr.my.phpcloud.com/Project_01/estore/paymentConfirm/'.$productId.'/0/'.$orderId);
    			$confirmadress);
    	$express->setCancelUrl(
    			//'http://comm-app.local/users/store/paymentCancel');
    			'http://bupiotr.my.phpcloud.com/Project_01/estore/payment-cancel');
    	// Send Order information to PayPal
    	$response = $paypalRequest->send($express);
    	$token = $response->getToken();
    	$paypalSession = new \Zend\Session\Container('paypal');
    	$paypalSession->tokenId = $token;
    	$paypalSession->orderId = $orderId;
    	// Redirect user to PayPal Express Checkout
    	$this->redirect()->toUrl('https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=' . $token);
    }
    	
    public function paymentConfirmAction()
    {
    	$productId = $this->params()->fromRoute('id');
    	// To capture Payer Information from PayPal
    	$paypalSession = new \Zend\Session\Container('paypal');
    	$paypalRequest = $this->getPaypalRequest();
    	$expressCheckoutInfo = 	new \SpeckPaypal\Request\GetExpressCheckoutDetails();
    	$expressCheckoutInfo->setToken($paypalSession->tokenId);
    	$response = $paypalRequest->send($expressCheckoutInfo);
    	//To capture express payment
    	$orderTable = $this->getServiceLocator()->get('OrdersTable');
    	$order = $orderTable->getStoreorders($paypalSession->orderId);
    	$paymentDetails = new \SpeckPaypal\Element\
    	PaymentDetails(array(
    			'amt' => $order->total
    	));
    	$token = $response->getToken();
    	$payerId = $response->getPayerId();
    	$captureExpress = new \SpeckPaypal\Request\
    	DoExpressCheckoutPayment(
    			array(
    					'token' => $token,
    					'payerId' => $payerId,
    					'paymentDetails' => $paymentDetails
    			));
    	$confirmPaymentResponse = $paypalRequest->send($captureExpress);
    	//To Save Order Information
    	$order->first_name = $response->getFirstName();
    	$order->last_name = $response->getLastName();
    	$order->ship_to_street = $response->getShipToStreet();
    	$order->ship_to_city = $response->getShipToCity();
    	$order->ship_to_state = $response->getShipToState();
    	$order->ship_to_zip = $response->getShipToZip();
    	$order->email = $response->getEmail();
    	$order->store_order_id = $paypalSession->orderId;
    	$order->status = 'completed';
    	$orderTable->saveStoreorders($order);
    	///////////////////////////////////////////////////////
    	$productTable = $this->getServiceLocator()->get('ProductsTable');
    	$product = $productTable->getStoreproducts($productId);
    	//////////////////////////////////////////////////////
    	$viewModel = new ViewModel(array('order'=>$order,'product'=>$product));
    	return $viewModel;
    }
    
    public function paymentCancelAction()
    {
    	$paypalSession = new \Zend\Session\Container('paypal');
    	$storeOrdersTG = $this->getServiceLocator()->get('OrdersTable');
    	$storeOrdersTG->update(
    			array('status' => 'cancelled'),
    			array('id' => $paypalSession->orderId));
    	$paypalSession->orderId = NULL;
    	$paypalSession->tokenId = NULL;
    	$view = new ViewModel();
    	return $view;
    }
    
    protected function getPaypalRequest()
    {
    	$config = $this->getServiceLocator()->get('config');
    	$paypalConfig = new \SpeckPaypal\Element\Config(
    			$config['speck-paypal-api']);
    	$adapter = new \Zend\Http\Client\Adapter\Curl();
    	$adapter->setOptions(array(
    			'curloptions' => array(
    					CURLOPT_SSL_VERIFYPEER => false,
    			)
    	));
    	$client = new \Zend\Http\Client;
    	$client->setMethod('POST');
    	$client->setAdapter($adapter);
    	$paypalRequest = new \SpeckPaypal\Service\Request;
    	$paypalRequest->setClient($client);
    	$paypalRequest->setConfig($paypalConfig);
    	return $paypalRequest;
    }
    
    public function addAction()
    {
    	$form = new StoreproductsForm();
    	 
    	$request = $this->getRequest();
    	 
    	if ($request->isPost()) {
    		$Storeproducts = new Storeproducts();
    		//$form->setInputFilter($Storeproducts->getInputFilter());
    		$form->setData($request->getPost());
    		 
    		if (!$form->isValid())
    		{
    			$viewModel = new ViewModel(array(
    					'error' => true,
    					'form' => $form,
    			));
    			$viewModel->setTemplate('estore/add');
    			return $viewModel;
    		}
    		else
    		{
    			$Storeproducts->exchangeArray($form->getData());
    			$ProductsTable = $this->getServiceLocator()->get('ProductsTable');
    			$ProductsTable->saveStoreproducts($Storeproducts);
    			 
    			// Redirect to list of products
    			return $this->redirect()->toRoute('estore');
    		}
    	}
    	$viewModel = new ViewModel(array('form' => $form));
    	return $viewModel;
    }
    
    public function deleteAction() {
    	
    	$id = (int) $this->params()->fromRoute('id', 0);
    	if (!$id) {
    		return $this->redirect()->toRoute('estore');
    	}
    
    	$request = $this->getRequest();
    	if ($request->isPost()) {
    		$del = $request->getPost('del', 'No');
    
    		if ($del == 'Yes') {
    			$id = (int) $request->getPost('id');
    			//$this->getUserTable()->deleteAlbum($id);
		    	$productTable = $this->getServiceLocator()->get('ProductsTable');
		    	$productTable->deleteStoreproducts($id);
    		}
    		// Redirect to list of users
    		return $this->redirect()->toRoute('estore');
    	}
    	//we are getting product w id from params
    	$productTable = $this->getServiceLocator()->get('ProductsTable');
    	$product = $productTable->getStoreproducts($id);
    	
    	$viewModel = new ViewModel(array('product' => $product,'id'=>$id,));
    	return $viewModel;
    	
    }
    
    public function getAuthService()
    {
    	if (! $this->authservice) {
    		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    		$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,'user','email','password', 'MD5(?)');
    		$authService = new AuthenticationService();
    		$authService->setAdapter($dbTableAuthAdapter);
    		$this->authservice = $authService;
    	}
    	return $this->authservice;
    }
    
    ///////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////PayPal
    ///////////////////////////////////////////////////////////////////////////////////////////
    
   
    
    public function fooAction()
    {
        // This shows the :controller and :action parameters in default route
        // are working when you browse to /store/store/foo
        return array();
    }
}
